package com.example.behaviour.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.behaviour.pojos.Message;
import com.example.behaviour.session.SessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class OnlineMessageHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        SessionFactory.getSession().bindID_CTX(ctx.channel().id(),ctx);
        log.info("ID_CTX绑定成功 ID {}",ctx.channel().id().toString());
    }

    /**
     * @param ctx
     * @author xiongchuan on 2019/4/28 16:10
     * @DESCRIPTION: 有服务端端终止连接服务器会触发此函数
     * @return: void
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        SessionFactory.getSession().unbind(ctx);
        ctx.close();
        log.info("服务端终止了服务");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        log.info("执行到了OnlineMessageHandler");
        TextWebSocketFrame frame = (TextWebSocketFrame)msg;
        JSONObject jsonObject = JSONObject.parseObject(frame.text());

        Message message = JSONObject.toJavaObject(jsonObject,Message.class);
        SessionFactory.getSession().bindNAME_ID(message.getUsername(),ctx.channel().id());
        log.info("Session {}",SessionFactory.getSession().toString());
//        TextWebSocketFrame textWebSocketFrame = new TextWebSocketFrame("NAME_ID绑定成功");
        log.info("NAME_ID绑定成功 NAME {} ID {}",message.getUsername(),ctx.channel().id().toString());

//        textWebSocketFrame.retain();
//        ctx.writeAndFlush(textWebSocketFrame);
        if(!message.isLoginFlag()){
            frame.retain();
            ctx.fireChannelRead(frame);
        }


    }


//    @Override
//    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
//
//        //cause.printStackTrace();
//        log.info("服务端发生异常【" + cause.getMessage() + "】");
//        ctx.close();
//    }

    /**
     * @param msg       需要发送的消息内容
     * @param channelId 连接通道唯一id
     * @author xiongchuan on 2019/4/28 16:10
     * @DESCRIPTION: 客户端给服务端发送消息
     * @return: void
     */
    public void channelWrite(ChannelId channelId, String msg) {

    }
}
